{% extends "app/base_site.html" %}

{% block title %} 布控 {% endblock title %}

{% block stylesheets %}
  {{ block.super }}
{% endblock stylesheets %}

{% block content %}
<style>
    #video_player{
        /*background-color: rgba(0,0,00,0.6);*/
        width: 100%;
        height: 100%;
        /*object-fit: fill;*/
        /*border-radius: 5px;*/
        border: 1px solid #f0f0f0;

    }
    #video_player:focus {
        outline: -webkit-focus-ring-color auto 0px;
    }
    #video_canvas{
        margin: 0 0;
        border: 2px solid darkred;
        position: absolute;
        top: 0;
        left: 10px;
        /*width: 800px;*/
        /*height: 400px;*/
        z-index: 1;
    }
    .video_canvas_menu{
        margin-top: 50px;
    }
    .video_canvas_box{

    }
</style>
<script>
    let streamCodeDict = {};//视频流
    let streamCode;

    let algorithmCodeDict = {};//算法
    let algorithmCode;

</script>

  <div class="right_col" role="main">
    <div class="">

      <div class="row">
        <div class="col-md-12 col-sm-12 col-xs-12">
          <div class="x_panel">
            <div class="x_title">
              <h2>{% if  "add" == handle %}添加{% else %}编辑{% endif %}布控</h2>
              <div class="clearfix"></div>
            </div>
            <div class="x_content">

              <div class="col-md-8 col-sm-8 col-xs-12">


                <div class="video_canvas_box">
                   <video id="video_player" controls autoplay>
                        Your browser is too old which doesn't support h5 video
                    </video>
                   <canvas id="video_canvas" width="0" height="0">
                        Your browser is too old which doesn't support h5 canvas
                    </canvas>
                </div>
                  <div class="video_canvas_menu">
                      <button id="adjust_video_canvas" type="button" class="btn btn-default btn-sm">区域对齐</button>
                      <button id="clear_video_canvas" type="button" class="btn btn-danger btn-sm">清空算法识别区域</button>
                  </div>


              </div>

              <div class="col-md-4 col-sm-4 col-xs-12" >

             <div class="form-horizontal form-label-left">
                 {% if  "edit" == handle %}
                                 <div class="form-group">
                      <label class="control-label col-md-3 col-sm-3 col-xs-12">布控ID</label>
                      <div class="col-md-9 col-sm-9 col-xs-12">
                          <span style="height: 34px;line-height: 34px;padding: 6px 0;">{{ control.id }}</span>
                      </div>
                    </div>
                {% endif %}

                    <div class="form-group">
                      <label class="control-label col-md-3 col-sm-3 col-xs-12">布控编号</label>
                      <div class="col-md-9 col-sm-9 col-xs-12">
                          <span style="height: 34px;line-height: 34px;padding: 6px 0;">{{ control.code }}</span>
                      </div>
                    </div>

                <div class="form-group">
                      <label class="control-label col-md-3 col-sm-3 col-xs-12">选择视频流</label>
                    <div class="col-md-9 col-sm-9 col-xs-12">
                        {% if  "add" == handle %}
                          <select id="select_stream" class="select2_single form-control" required="required" >
                              {% if streams|length == 0 %}
                                  <option value="-1">暂无视频流</option>
                              {% else %}
                                  <option value="0">请选择视频流</option>

                                {% for stream in streams %}
                                    <script>
                                        streamCode = '{{ stream.code }}';
                                        streamCodeDict[streamCode] = {
                                            'code':streamCode,
                                            "app":'{{ stream.app }}',
                                            "name":'{{ stream.name }}',
                                            "video":'{{ stream.video }}',
                                            "audio":'{{ stream.audio }}',
                                            "httpFlvUrl":'{{ stream.httpFlvUrl }}',
                                            "wsMp4Url":'{{ stream.wsMp4Url }}',
                                        }
                                    </script>
                                    <option value="{{ stream.code }}">{{ stream.app }}/{{ stream.name }}</option>
                                {% endfor %}
                              {% endif %}
                          </select>
                     {% else %}
                          <select id="select_stream"  disabled="disabled"  class="select2_single form-control" >
                            <option selected value="{{ control.stream_app }}_{{ control.stream_name }}">{{ control.stream_app }}/{{ control.stream_name }}</option>
                          </select>
                     {% endif %}
                   </div>
               </div>


                <div class="form-group">
                  <label class="control-label col-md-3 col-sm-3 col-xs-12">视频信息</label>
                  <div class="col-md-9 col-sm-9 col-xs-12">
                         <input id="video"  type="text" disabled="disabled" value="{{ control.stream_video }}" class="form-control">
                  </div>
                </div>

                <div class="form-group">
                  <label class="control-label col-md-3 col-sm-3 col-xs-12">音频信息</label>
                  <div class="col-md-9 col-sm-9 col-xs-12">
                       <input id="audio"  type="text" disabled="disabled" value="{{ control.stream_audio }}" class="form-control">
                  </div>
                </div>



                <div class="form-group">
                  <label class="control-label col-md-3 col-sm-3 col-xs-12">播放地址</label>
                  <div class="col-md-9 col-sm-9 col-xs-12">
                       <input id="flvUrl"  type="url" disabled="disabled" value="{{ control_stream_flvUrl }}" class="form-control">
                  </div>
                </div>

                    <div class="form-group">
                      <div class="col-md-9 col-sm-9 col-xs-12 col-md-offset-3">
                            <button id="play" type="button" class="btn btn-default btn-sm"><i class="fa fa-play"></i> 播放视频 </button>
                            <button id="stop" type="button" class="btn btn-default btn-sm"><i class="fa fa-stop"></i> 停止播放 </button>
                      </div>
                    </div>
                 <div class="ln_solid"></div>


                      <div class="form-group">
                      <label class="control-label col-md-3 col-sm-3 col-xs-12">选择算法
                      </label>

                      <div class="col-md-9 col-sm-9 col-xs-12">

                        <select id="select_algorithm"  class="select2_single form-control" required="required"  tabindex="-1">
                            <option value="0">请选择算法</option>
                            {% for algorithm in algorithms %}
                               <script>
                                    algorithmCode = '{{ algorithm.code }}';
                                    algorithmCodeDict[algorithmCode] = {
                                        "code":algorithmCode,
                                        "name":'{{ algorithm.name }}',
                                        "object_count":'{{ algorithm.object_count }}',
                                        "objects":'{{ algorithm.objects }}',
                                    }
                                </script>

                                <option {% if algorithm.code == control.algorithm_code %} selected {% endif %} value="{{ algorithm.code }}">{{ algorithm.name }}</option>
                            {% endfor %}
                        </select>


                      </div>
                    </div>


                    <div class="form-group">
                      <label class="control-label col-md-3 col-sm-3 col-xs-12">选择目标
                      </label>

                      <div class="col-md-9 col-sm-9 col-xs-12">

                        <select id="select_object"  class="select2_single form-control" required="required"  tabindex="-1">
                            <option value="0">请选择目标</option>
                            {% for object in old_objects %}
                                <option {% if object == control.object_code %} selected {% endif %} value="{{ object }}">{{ object }}</option>
                            {% endfor %}
                        </select>


                      </div>
                    </div>


                   <div class="form-group">
                      <label class="col-md-3 col-sm-3 col-xs-12 control-label">是否推流
                      </label>
                      <div class="col-md-9 col-sm-9 col-xs-12">

                        <div class="radio">
                          <label>
                            <input type="radio" {% if control.push_stream == 0 %} checked="checked" {% endif %} value="0" name="push-stream"> 算法处理的视频不推流
                          </label>
                        </div>

                        <div class="radio">
                          <label>
                            <input type="radio" {% if control.push_stream == 1 %} checked="checked" {% endif %} value="1" name="push-stream"> 算法处理的视频推流
                          </label>
                        </div>

                      </div>
                    </div>

              <div class="form-group">
                  <label class="control-label col-md-3 col-sm-3 col-xs-12">报警间隔(秒)</label>
                  <div class="col-md-9 col-sm-9 col-xs-12">
                       <input id="min_interval"  type="number" value="{{ control.min_interval }}" class="form-control" >
                  </div>
                </div>

                 <div class="form-group">
                  <label class="control-label col-md-3 col-sm-3 col-xs-12">分类阈值</label>
                  <div class="col-md-9 col-sm-9 col-xs-12">
                       <input id="class_thresh"  type="number" value="{{ control.class_thresh }}" class="form-control" >
                  </div>
                </div>

              <div class="form-group">
                  <label class="control-label col-md-3 col-sm-3 col-xs-12">IOU阈值</label>
                  <div class="col-md-9 col-sm-9 col-xs-12">
                       <input id="overlap_thresh"  type="number" value="{{ control.overlap_thresh }}" class="form-control" >
                  </div>
                </div>

                     <div class="form-group">
                      <label class="control-label col-md-3 col-sm-3 col-xs-12" for="textarea">备注
                      </label>
                      <div class="col-md-9 col-sm-9 col-xs-12">
                        <textarea id="remark" required="required" name="textarea" class="form-control col-md-7 col-xs-12">{{ control.remark }}</textarea>

                      </div>
                    </div>


                    <div class="ln_solid"></div>
                    <div class="form-group">
                      <div class="col-md-9 col-sm-9 col-xs-12 col-md-offset-3">
                          <button id="handle_control" type="button" class="btn btn-success btn-sm">保存</button>
                      </div>
                    </div>

                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
{% endblock content %}

{% block javascripts %}
  {{ block.super }}

<script src="/static/lib/wsPlayer/mp4box.all.min.js"></script>
<script src="/static/lib/wsPlayer/wsPlayer.js"></script>

<script>
    let old_control_code= '{{ control.code }}';// 布控编号
    let old_control_polygon = '{{ control.polygon }}';// 布控多边形坐标点
    let old_control_stream_flvUrl = '{{ control_stream_flvUrl }}';// 已经布控的数据才存在该地址
    let handle = '{{ handle }}';// 操作类型 add 或 edit

    let ele_video_canvas=document.getElementById("video_canvas");
    let ele_adjust_video_canvas = $("#adjust_video_canvas");
    let ele_clear_video_canvas = $("#clear_video_canvas");
    //得到画布的上下文,上下文有两个 2d和3d
    //所有的图形绘制都是通过ctx属性或者方法进行设置的，和canvas标签没有关系了
    let ctx=ele_video_canvas.getContext("2d");
    let polygon_lineArray = [];//存储多边形的每一条边
    let polygon_lineMaxCount = 4;//多边形的边数
    let polygon_line = null;//多边形的边，临时变量

    let eleVideoPlayer= document.getElementById("video_player");
    let eleSelectStream = $("#select_stream");// select  选择视频流
    let eleFlvUrl= $("#flvUrl");// input
    let eleVideo = $("#video");// input
    let eleAudio = $("#audio");// input
    let eleBtnPlay = $("#play");//button
    let eleBtnStop = $("#stop");//button

    let eleSelectAlgorithm = $("#select_algorithm");// select 选择算法
    let eleSelectObject = $("#select_object");// select 选择算法
    let ele_min_interval = $("#min_interval");
    let ele_class_thresh = $("#class_thresh");
    let ele_overlap_thresh = $("#overlap_thresh");

    let elePushStream = $('input[type=radio][name=push-stream]');//radio
    let pushStream = $('input[type=radio][name=push-stream]:checked').val();
    let ele_remark = $("#remark");// textarea

    let eleBtnHandleControl = $("#handle_control");//添加或更新布控数据

    class MyPoint{
        constructor(x,y) {
            this.x = x;
            this.y = y;
        }
    }
    //创建线段类  多个线段对象相互连接就成为了点
    class MyLine{
        x2;
        y2;
        //构造方法设置第一个点
        constructor(x,y) {
          this.x=x;
          this.y=y;
        }
        //更新 设置第二给点
        LineUpdate=function (x,y){
          this.x2=x;
          this.y2=y;
        }


        //绘制
        LineDraw=function (){
            ctx.lineWidth = 2;//设置线条宽度
            //ctx.font = "normal bold 40px Arial";//设置字体
            ctx.strokeStyle="red" //设置颜色

          ctx.beginPath();
          ctx.moveTo(this.x,this.y);//第一个点
          ctx.lineTo(this.x2,this.y2); //点三个
          ctx.stroke(); //开始绘制(把前面点连接)
        }

    }

    //清空绘制区域数据
    function f_clearVideoCanvas() {
        ctx.clearRect(0,0,ele_video_canvas.width,ele_video_canvas.height);
        polygon_lineArray = [];

    }
    //窗口对齐->清空绘制区域数据
    function f_adjustVideoCanvas() {
        //执行窗口对齐以后，此前的绘制区域数据，可能不在对应，因此需要删除
        let w = eleVideoPlayer.offsetWidth;
        let h = eleVideoPlayer.offsetHeight;
        console.log("f_adjustVideoCanvas",w,h)
        w = w - 1.8;
        h = h - 2.2;
        ele_video_canvas.setAttribute("width",String(w));
        ele_video_canvas.setAttribute("height",String(h));
        f_clearVideoCanvas();
    }
    function f_reDrawVideoCanvas() {
        console.log("f_reDrawVideoCanvas() polygon_lineArray.length=",polygon_lineArray.length);
        ctx.clearRect(0,0,ele_video_canvas.width,ele_video_canvas.height);
        for (let i = 0; i < polygon_lineArray.length; i++) {
            let line = polygon_lineArray[i];
            line.LineDraw();
        }
    }

    //画布鼠标监听 按下  按下后绘制图形
    ele_video_canvas.addEventListener("mousedown",function (event){
        if(polygon_lineArray.length < polygon_lineMaxCount){
            if(polygon_line===null){
                let x = event.offsetX;
                let y = event.offsetY;
                polygon_line=new MyLine(x,y);
            }
        }
    });
    // 获取鼠标在画布移动的坐标
    ele_video_canvas.addEventListener("mousemove", function(event){
        if(polygon_line){
            let x = event.offsetX;
            let y = event.offsetY;

            f_reDrawVideoCanvas();
            polygon_line.LineUpdate(x,y);
            polygon_line.LineDraw();
        }


    });
    //鼠标左键弹起时候
    ele_video_canvas.addEventListener("mouseup",function (event){
        if(polygon_line){

            f_reDrawVideoCanvas();
            let x = event.offsetX;
            let y = event.offsetY;
            if(polygon_lineArray.length === polygon_lineMaxCount-1){//还差一条边的时候，将第一条边的起点作为最后一条边的终点
                let firstLine = polygon_lineArray[0];
                x = firstLine.x;
                y = firstLine.y;
            }
            polygon_line.LineUpdate(x,y);
            polygon_line.LineDraw();
            polygon_lineArray.push(polygon_line);

            console.log("mouseup() polygon_lineArray.length=",polygon_lineArray.length);
            if(polygon_lineArray.length < polygon_lineMaxCount){
                polygon_line=new MyLine(x,y);
            }else{
                polygon_line=null;
            }
        }
    })
    //绘制区域与视频窗口对齐
    ele_adjust_video_canvas.click(function () {
        f_adjustVideoCanvas();
    })
    ele_clear_video_canvas.click(function () {
        f_clearVideoCanvas();
    })

    eleSelectStream.change(function () {

        streamCode = $(this).val();
        let stream = streamCodeDict[streamCode];
        if (stream) {
            let url = stream["wsMp4Url"]
            eleFlvUrl.val(url)
            eleVideo.val(stream["video"])
            eleAudio.val(stream["audio"])
            f_playStart(url);
        }else{
            eleFlvUrl.val("")
            eleVideo.val("")
            eleAudio.val("")
            f_playStop();
        }

        for (let i = 0; i < 10; i++) {
            setTimeout(function () {
                f_adjustVideoCanvas();
            }, i*200);
        }

    });

    eleSelectAlgorithm.change(function () {

        algorithmCode = $(this).val();
        try {
            let objects = algorithmCodeDict[algorithmCode]["objects"]
            let objects_array = objects.split(",");
            //console.log(algorithmCode)
            //console.log(objects)
            //console.log(objects_array)
            let html = "<option value=\"0\">请选择目标</option>";
            for (let i = 0; i < objects_array.length; i++) {
                let object = objects_array[i];
               html += "<option value=\""+object+"\">"+object+"</option>";
            }
            eleSelectObject.html(html)

        }catch (e) {
            console.log("eleSelectAlgorithm.change() error",e);
            let html = "<option value=\"0\">请选择目标</option>";
            eleSelectObject.html(html)
        }
    });

    eleBtnPlay.click(function () {
        f_playStart(eleFlvUrl.val());
    });
    eleBtnStop.click(function (){
        f_playStop();
    });

    elePushStream.change(function () {
        pushStream = $(this).val();
    });

    eleBtnHandleControl.click(function () {// 添加或更新
        f_postHandleControl();
    });

    function f_postHandleControl() {
        streamCode = eleSelectStream.val().trim();//typeof string
        if(streamCode==="-1"){
            myAlert("暂无视频流","error");
            return;
        }else if(streamCode==="0"){
            myAlert("请选择视频流","error");
            return;
        }
        algorithmCode = eleSelectAlgorithm.val().trim();//typeof string
        if(algorithmCode==="0"){
            myAlert("请选择算法","error");
            return;
        }
        objectCode = eleSelectObject.val().trim();//typeof string
        if(objectCode==="0"){
            myAlert("请选择目标","error");
            return;
        }
        let minInterval = parseInt(ele_min_interval.val());
        if(isNaN(minInterval)){
            myAlert("报警间隔时间不能为空","error");
            return;
        }
        if(minInterval<10){
            myAlert("报警间隔时间不能小于10秒","error");
            return;
        }

        let classThresh = parseFloat(ele_class_thresh.val());
        console.log(typeof classThresh,classThresh)

        if(isNaN(classThresh)){
            myAlert("分类阈值不能为空","error");
            return;
        }

        if(classThresh<=0){
            myAlert("分类阈值不能小于等于0","error");
            return;
        }
        if(classThresh>1){
            myAlert("分类阈值不能大于1","error");
            return;
        }

        let overlapThresh = parseFloat(ele_overlap_thresh.val());

        if(isNaN(overlapThresh)){
            myAlert("IOU阈值不能为空","error");
            return;
        }

        if(overlapThresh<=0){
            myAlert("IOU阈值不能小于等于0","error");
            return;
        }
        if(overlapThresh>1){
            myAlert("IOU阈值不能大于1","error");
            return;
        }

        let remark = ele_remark.val().trim();

        if(polygon_lineArray.length!==polygon_lineMaxCount){
            myAlert("请绘制算法识别区域","error");
            return;
        }
        let video_canvas_width = ele_video_canvas.width;
        let video_canvas_height = ele_video_canvas.height
        let points = [];// x1,y1,x2,y2,x3,y3,x4,y4
        for (let i = 0; i < polygon_lineArray.length; i++) {
            let line = polygon_lineArray[i];
            points.push((line.x/video_canvas_width).toFixed(4));
            points.push((line.y/video_canvas_height).toFixed(4));
        }
        let polygon = points.join(",");

        let data = {
            "controlCode":old_control_code,
            "algorithmCode":algorithmCode,
            "objectCode":objectCode,
            "pushStream":pushStream,
            "polygon":polygon,
            "minInterval":minInterval,
            "classThresh":classThresh,
            "overlapThresh":overlapThresh,
            "remark":remark
        }

        let handleUrl;
        if("add" === handle){
            handleUrl = "/api/postAddControl";
            let stream = streamCodeDict[streamCode];
            if (stream){
                data["streamApp"] = stream["app"]
                data["streamName"] = stream["name"]
                data["streamVideo"] = stream["video"]
                data["streamAudio"] = stream["audio"]
            }else{
                return;
            }
        }else if("edit" === handle){
            handleUrl = "/api/postEditControl";
        }else{
            return;
        }


        $.ajax({
           url: handleUrl,
           type: "post",
           async: true,
           data: data,
           dataType: "json",
           timeout: "3000",
           error: function () {
                myAlert("网络异常，请确定网络正常！","error");
           },
           success: function (res) {
               if(1000 === res.code){
                    myAlert(res.msg,"success");

               }else{
                    myAlert(res.msg,"error");
               }
           }
        });

    }
        let mWsVideoPlayer = null;
        let mVideoUrl = null;
    function f_playStart(url){
        console.log("f_playStart---->",url);
        mVideoUrl = url;
        if(mVideoUrl.startsWith("ws://")){
            if(mWsVideoPlayer){
                try {
                    mWsVideoPlayer.close();
                }catch (e) {
                    console.log("f_playStart() err:",e);
                }
            }
            mWsVideoPlayer = new wsPlayer("video_player", mVideoUrl);
            mWsVideoPlayer.open();
        }
    }
    function f_playStop(){
        console.log("f_playStop");
        if(mVideoUrl.startsWith("ws://")){
            if(mWsVideoPlayer){
                mWsVideoPlayer.close();
                mWsVideoPlayer = null;
            }
        }
    }

    window.onresize = function () {
        f_adjustVideoCanvas();
    }

    window.onload = function () {
        if(old_control_stream_flvUrl!==""){//编辑布控
            f_playStart(old_control_stream_flvUrl);
            setTimeout(function () {
                f_adjustVideoCanvas();
                if(old_control_polygon!==""){
                    console.log("old_control_polygon restore1=",old_control_polygon)
                    let xys = old_control_polygon.split(",");
                    let lineCount = xys.length / 2;
                    if(lineCount > 3){
                        let video_canvas_width = ele_video_canvas.width;
                        let video_canvas_height = ele_video_canvas.height

                        let points = [];
                        for (let i = 0; i < lineCount; i++) {
                            let x_index = i * 2;
                            let y_index = x_index+1;
                            let x = parseInt(parseFloat(xys[x_index]) * video_canvas_width);
                            let y = parseInt(parseFloat(xys[y_index]) * video_canvas_height);
                            let p = new MyPoint(x,y);
                            points.push(p);
                        }

                        console.log("old_control_polygon points=",points)

                        for (let i = 0; i < lineCount; i++) {
                            let p1 = points[i];
                            let p2;
                            if(i===(lineCount-1)){
                                p2 = points[0];
                            }else{
                                p2 = points[i+1];
                            }
                            let line = new MyLine(p1.x,p1.y);
                            line.LineUpdate(p2.x,p2.y);
                            polygon_lineArray.push(line);
                        }

                    }
                    console.log("old_control_polygon restore2=",polygon_lineArray)
                }
                f_reDrawVideoCanvas();
            }, 1200);
        }else{//新增布控
            f_adjustVideoCanvas();
        }
    }
</script>

{% endblock javascripts %}
